//
//  ChangePwdViewController.m
//  NOAHWM
//
//  Created by Ryan on 13-5-23.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "ResetPwdViewController.h"
#import "JSON.h"
#import "NSString+MD5.h"

#define kModifyDynPwdDownloaderKey  @"ModifyDynPwdDownloaderKey"
#define kChangePwdDownloaderKey     @"ChangePwdDownloaderKey"

@interface ResetPwdViewController ()

@end

@implementation ResetPwdViewController

@synthesize dynPwd,phoneNum;
@synthesize dynPwdField,pwdField,rePwdField,resendButton,commitButton;

- (NSString *)checkPasswordValid
{
    /**
     动态密码：4-4
     新密码：6-50
     */
    if(dynPwdField.text.length == 0)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000001E"],@"验证码"];
    else if(dynPwdField.text.length != 4)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000012E"],@"4位",@"验证码"];
    else if(![dynPwdField.text isEqualToString:self.dynPwd])
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000014E"],@"验证码"];
    else if(pwdField.text.length == 0)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000001E"],@"新密码"];
    else if(pwdField.text.length < 6 || pwdField.text.length > 50)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000012E"],@"6-50位",@"新密码"];
    else if(rePwdField.text.length == 0)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000001E"],@"确认密码"];
    else if(rePwdField.text.length < 6 || rePwdField.text.length > 50)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000012E"],@"6-50位",@"确认密码"];
    else if(![pwdField.text isEqualToString:rePwdField.text])
        return [kRegisterPromptDict objectForKey:@"F000013E"];
    else
        return nil;
}

- (void)enableResendButton
{
    self.resendButton.enabled = YES;
}

#pragma mark - IBAction methods
- (IBAction)resendButtonClicked:(id)sender
{
    [self.dynPwdField resignFirstResponder];
    [self.pwdField resignFirstResponder];
    [self.rePwdField resignFirstResponder];
    
    self.resendButton.enabled = NO;
    [self performSelector:@selector(enableResendButton) withObject:nil afterDelay:30.f];
    
    
    NSString *suburl = [NSString stringWithFormat:kBeginFindPwdUrl,@"jsonp",self.phoneNum];
    suburl = [suburl stringByAppendingString:@"app000004"];
    NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:kModifyDynPwdDownloaderKey];
}

- (IBAction)commitButtonClicked:(id)sender
{
    [self.dynPwdField resignFirstResponder];
    [self.pwdField resignFirstResponder];
    [self.rePwdField resignFirstResponder];
    
    NSString *validString = [self checkPasswordValid];
    if(validString)
    {
        [[RYHUDManager sharedManager] showWithMessage:validString customView:nil hideDelay:2.f];
    }
    else
    {
        NSString *oldpwd = self.dynPwdField.text;
        NSString *newpwd = self.pwdField.text;
        NSString *repwd = self.rePwdField.text;
        NSString *md5Newpwd = [NSString md5HexDigest:newpwd];
        NSString *md5Repwd = [NSString md5HexDigest:repwd];
        
        NSString *subUrl = [NSString stringWithFormat:kResetPwdUrl,@"jsonp",self.phoneNum,md5Newpwd,md5Repwd,oldpwd];
        subUrl = [subUrl stringByAppendingString:@"app000005"];
        NSString *reseturl = [NSString stringWithFormat:@"%@%@",kServerAddress,subUrl];
        reseturl = [reseturl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:reseturl delegate:self purpose:kChangePwdDownloaderKey];
        [[RYHUDManager sharedManager]startedNetWorkActivityWithText:@"密码修改中..."];
    }
}

#pragma mark - BaseViewController methods
- (void)leftItemTapped
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(enableResendButton) object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIViewController methods

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setNaviTitle:@"重设密码"];
    [self setLeftNaviItemWithTitle:nil imageName:@"Icon_Back"];
    [self setRightNaviItemWithTitle:nil imageName:nil];
    [self addSwipePopGesture];
    [self performSelector:@selector(enableResendButton) withObject:nil afterDelay:30.f];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.isViewLoaded && !self.view.window)
    {
        [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
        self.view = nil;
        self.dynPwdField = nil;
        self.pwdField = nil;
        self.rePwdField = nil;
        self.resendButton = nil;
        self.commitButton = nil;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    self.dynPwdField = nil;
    self.pwdField = nil;
    self.rePwdField = nil;
    self.resendButton = nil;
    self.commitButton = nil;
}

- (void)dealloc
{
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    [dynPwdField release];
    [pwdField release];
    [rePwdField release];
    [resendButton release];
    [commitButton release];
    [dynPwd release];
    [phoneNum release];
    [super dealloc];
}

#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    if([downloader.purpose isEqualToString:kModifyDynPwdDownloaderKey])
    {
        NSDictionary *dict = [str JSONValue];
        if([[dict objectForKey:@"result"] isEqualToString:@"1"])
        {
            self.dynPwd = [dict objectForKey:@"verifycode"];
        }
        else
        {
            self.dynPwd = nil;
        }
        [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
    }
    else
    {
        NSDictionary *dict = [str JSONValue];
        [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
        if([[dict objectForKey:@"result"] isEqualToString:@"1"])
        {
            /**
             --如果当前忘记密码入口来自登录界面，密码修改成功之后dismis navigation controller
             --如果当前忘记密码入口来自修改密码界面，密码修改成功之后pop至personal info 页
             */
            if(self.presentingViewController)
            {
                //来自登录页面
                [self.navigationController dismissModalViewControllerAnimated:YES];
            }
            else
            {
                //来自修改密码页面
                NSArray *vcs = [self.navigationController viewControllers];
                [self.navigationController popToViewController:[vcs objectAtIndex:vcs.count - 4] animated:YES];
            }
        }
        
    }
}
- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
}
@end
